/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.boxin.ims.modules.momarketing.entity.CustomPage;
import com.boxin.ims.modules.momarketing.service.CustomPageService;
import com.boxin.ims.modules.wechat.entity.UserBusiness;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatConfig;
import com.boxin.ims.modules.wechat.entity.WechatMenu;
import com.boxin.ims.modules.wechat.service.BusinessConfigService;
import com.boxin.ims.modules.wechat.service.NewsReplyService;
import com.boxin.ims.modules.wechat.service.UserBusinessService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatConfigService;
import com.boxin.ims.modules.wechat.service.WechatMenuService;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatMenuUtils;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 微信自定义菜单Controller
 * @author Jakemanse
 * @version 2013-09-11
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/wechat/wechatMenu")
public class WechatMenuController extends BaseController {

	@Autowired
	private WechatMenuService wechatMenuService;
	
	@Autowired
	WeChatService weChatService;
	
	@Autowired
	NewsReplyService newsReplyService;
	
	@Autowired
	WechatConfigService wechatConfigService;
	
	@Autowired
	UserBusinessService userBusinessService;
	
	@Autowired
	BusinessConfigService businessConfigService;
	
	@Autowired
	CustomPageService customPageService;
	
	@ModelAttribute
	public WechatMenu get(@RequestParam(required=false) Long id) {
		if (id != null){
			return wechatMenuService.get(id);
		}else{
			return new WechatMenu();
		}
	}
	
	@RequiresPermissions("wechat:wechatMenu:view")
	@RequestMapping(value = {"list", ""})
	public String list(WechatMenu wechatMenu, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		User user = UserUtils.getUser();
		wechatMenu.setUser(user);
        List<WechatMenu> wmList = wechatMenuService.findAll(wechatMenu);
        List<WechatMenu> list = Lists.newArrayList();
        WechatMenu.sortList(list, wmList, 0L);
        model.addAttribute("list", wmList);
        model.addAttribute("wechatMenu", wechatMenu);
		return "modules/wechat/wechatMenuList";
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-12  下午1:55:33
	 * @function <p> 生成微信菜单  </p>
	 * @param wechatMenu
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value =   "generate" )
	public String generate(WechatMenu wechatMenu,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		User user = UserUtils.getUser();
		List<WechatMenu> wmList = wechatMenuService.findAllByUserId(user.getId());
		
		String params = WechatMenuUtils.menuParams(wmList);
		WeChat wechat = 	weChatService.getWeChatByUserId(UserUtils.getUser().getId());
		String appid = wechat.getAppId();
		String secret= wechat.getAppSecret();
		try {
			String accessToken = TokenUtils.getAPIToken(appid, secret);
			WechatMenuUtils.createMenu(params, accessToken);
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "微信菜单更新失败。");
		}
		
		return list(wechatMenu,request,response,model);
	}

	@RequiresPermissions("wechat:wechatMenu:view")
	@RequestMapping(value = "form")
	public String form(WechatMenu wechatMenu,HttpServletRequest request, HttpServletResponse response,  Model model) {
		User user = UserUtils.getUser();
		if(wechatMenu.getUser() == null){
			wechatMenu.setUser(user);
		}
		
		String addFlag = "1";	//是否还能添加菜单	1：是 0：否
		
		WeChat wechat = weChatService.getWeChatByUserId(user.getId());
		WechatConfig wechatConfig=new WechatConfig();
		wechatConfig.setWeChat(wechat);
		
		//定义的服务
		//List<BusinessConfig> configList = 	businessConfigService.findAll();
		//定义的回复
		List<WechatConfig> wechatList	=  wechatConfigService.find(wechatConfig);	//回复内容列表
		wechatList =  (wechatList == null) ? new ArrayList<WechatConfig>() : wechatList;
		
		List<UserBusiness> businessList = userBusinessService.findAllByUserId(user.getId());		//当前用户所拥有的服务
		
//		for(WechatConfig config :wechatList){
//			BusinessConfig bcg = new BusinessConfig();
//			bcg.setKeywords(config.getUpContent());
//			configList.add(bcg);
//		}
//		
//		//业务 活动 回复
		for(WechatConfig config :wechatList){
			if(StringUtils.isNotEmpty(config.getUpContent())){
				UserBusiness ub = new UserBusiness();
				ub.setName(config.getUpContent());
				businessList.add(ub);
			}
		}
		
		
		//页面 活动 获得积分导航
		List<CustomPage> pageList = 	customPageService.findAllByUserId(user.getId());
		for(CustomPage page : pageList){
			UserBusiness ub = new UserBusiness();
			ub.setName(page.getName()+"--活动");
			businessList.add(ub);
		}
		
		
		
		String sub = request.getParameter("sub");
		if("1".equals(sub)){	//添加子菜单
			List<WechatMenu>  mainMenus =  wechatMenuService.findMainMenusByUserId(user.getId());
			model.addAttribute("sub", "1");
			model.addAttribute("mainMenus", mainMenus);
			
			
		}else{
			
			//如果大于3个主菜单 则不能再添加
			List temps = wechatMenuService.findMainMenusByUserId(user.getId());
			if(temps != null && temps.size() >=3){
				if(wechatMenu.getId() == null ){	//新建
					model.addAttribute("message", "主菜单最多不能超过3个!");
					addFlag = "0";
					wechatMenu.setSort(temps.size()-1);
				}
			} 
		}
		
		
		model.addAttribute("addFlag", addFlag);
		model.addAttribute("wechatMenu", wechatMenu);
		model.addAttribute("wechatList", wechatList);
//		model.addAttribute("configList", configList);		//关键词
		model.addAttribute("businessList", businessList);		//关键词
		return "modules/wechat/wechatMenuForm";
	}

	@RequiresPermissions("wechat:wechatMenu:edit")
	@RequestMapping(value = "save")
	public String save(WechatMenu wechatMenu, Model model,HttpServletRequest request, HttpServletResponse response,  RedirectAttributes redirectAttributes) {
		
		if (!beanValidator(model, wechatMenu)){
			return form(wechatMenu,request,response, model);
		}
		wechatMenuService.save(wechatMenu);
		addMessage(redirectAttributes, "保存菜单'" + wechatMenu.getName() + "'成功");
		return "redirect:"+Global.ADMIN_PATH+"/wechat/wechatMenu/?repage";
	}
	
	@RequiresPermissions("wechat:wechatMenu:edit")
	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		List<WechatMenu> subMenus = 	wechatMenuService.findChildrenByParentId(id);
		if(subMenus != null && !subMenus.isEmpty()){
			addMessage(redirectAttributes, "请先删除子菜单再删除本菜单,删除失败");
		}else{
			wechatMenuService.delete(id);
			addMessage(redirectAttributes, "删除微信自定义菜单成功");
		}
		return "redirect:"+Global.ADMIN_PATH+"/wechat/wechatMenu/?repage";
	}
	
	
	

}
